function _arrayLikeToArray(r, a) {
  (null == a || a > r.length) && (a = r.length);
  for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
  return n;
}
function _arrayWithoutHoles(r) {
  if (Array.isArray(r)) return _arrayLikeToArray(r);
}
function asyncGeneratorStep(n, t, e, r, o, a, c) {
  try {
    var i = n[a](c),
      u = i.value;
  } catch (n) {
    return void e(n);
  }
  i.done ? t(u) : Promise.resolve(u).then(r, o);
}
function _asyncToGenerator(n) {
  return function () {
    var t = this,
      e = arguments;
    return new Promise(function (r, o) {
      var a = n.apply(t, e);
      function _next(n) {
        asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
      }
      function _throw(n) {
        asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
      }
      _next(void 0);
    });
  };
}
function _iterableToArray(r) {
  if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
}
function _nonIterableSpread() {
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _readOnlyError(r) {
  throw new TypeError('"' + r + '" is read-only');
}
function _regenerator() {
  /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
  var e,
    t,
    r = "function" == typeof Symbol ? Symbol : {},
    n = r.iterator || "@@iterator",
    o = r.toStringTag || "@@toStringTag";
  function i(r, n, o, i) {
    var c = n && n.prototype instanceof Generator ? n : Generator,
      u = Object.create(c.prototype);
    return _regeneratorDefine(u, "_invoke", function (r, n, o) {
      var i,
        c,
        u,
        f = 0,
        p = o || [],
        y = false,
        G = {
          p: 0,
          n: 0,
          v: e,
          a: d,
          f: d.bind(e, 4),
          d: function (t, r) {
            return i = t, c = 0, u = e, G.n = r, a;
          }
        };
      function d(r, n) {
        for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) {
          var o,
            i = p[t],
            d = G.p,
            l = i[2];
          r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0));
        }
        if (o || r > 1) return a;
        throw y = true, n;
      }
      return function (o, p, l) {
        if (f > 1) throw TypeError("Generator is already running");
        for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) {
          i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u);
          try {
            if (f = 2, i) {
              if (c || (o = "next"), t = i[o]) {
                if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object");
                if (!t.done) return t;
                u = t.value, c < 2 && (c = 0);
              } else 1 === c && (t = i.return) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1);
              i = e;
            } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break;
          } catch (t) {
            i = e, c = 1, u = t;
          } finally {
            f = 1;
          }
        }
        return {
          value: t,
          done: y
        };
      };
    }(r, o, i), true), u;
  }
  var a = {};
  function Generator() {}
  function GeneratorFunction() {}
  function GeneratorFunctionPrototype() {}
  t = Object.getPrototypeOf;
  var c = [][n] ? t(t([][n]())) : (_regeneratorDefine(t = {}, n, function () {
      return this;
    }), t),
    u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
  function f(e) {
    return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
  }
  return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine(u), _regeneratorDefine(u, o, "Generator"), _regeneratorDefine(u, n, function () {
    return this;
  }), _regeneratorDefine(u, "toString", function () {
    return "[object Generator]";
  }), (_regenerator = function () {
    return {
      w: i,
      m: f
    };
  })();
}
function _regeneratorDefine(e, r, n, t) {
  var i = Object.defineProperty;
  try {
    i({}, "", {});
  } catch (e) {
    i = 0;
  }
  _regeneratorDefine = function (e, r, n, t) {
    if (r) i ? i(e, r, {
      value: n,
      enumerable: !t,
      configurable: !t,
      writable: !t
    }) : e[r] = n;else {
      function o(r, n) {
        _regeneratorDefine(e, r, function (e) {
          return this._invoke(r, n, e);
        });
      }
      o("next", 0), o("throw", 1), o("return", 2);
    }
  }, _regeneratorDefine(e, r, n, t);
}
function _toConsumableArray(r) {
  return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
}
function _unsupportedIterableToArray(r, a) {
  if (r) {
    if ("string" == typeof r) return _arrayLikeToArray(r, a);
    var t = {}.toString.call(r).slice(8, -1);
    return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
  }
}

var getRuntime = function getRuntime() {
  if (typeof uni !== 'undefined') return uni;
  if (typeof wx !== 'undefined') return wx;
  throw new Error('Unsupported runtime');
};
// 判断使用 uni 还是 wx
var platformApi = getRuntime();

var ErrorTypes$1 = {
  BLUETOOTH_CONNECTION_FAILED: 'BLUETOOTH_CONNECTION_FAILED',
  DEVICE_CONNECTION_FAILED: 'DEVICE_CONNECTION_FAILED',
  DEVICE_NOT_FOUND: 'DEVICE_NOT_FOUND',
  SERVICE_NOT_FOUND: 'SERVICE_NOT_FOUND',
  CHARACTERISTIC_NOT_FOUND: 'CHARACTERISTIC_NOT_FOUND',
  NOTIFICATION_ENABLE_FAILED: 'NOTIFICATION_ENABLE_FAILED',
  WRITE_DATA_FAILED: 'WRITE_DATA_FAILED',
  NO_MEASUREMENT_DATA: 'NO_MEASUREMENT_DATA'
};

/**
 * 蓝牙连接功能模块
 * @param {Object} config - 配置项对象
 * @param {function} config.errorHandler - 异常处理函数
 * @returns {Object} - 包含初始化蓝牙方法的对象
 */
function bluetoothConnection (config) {
  var errorHandler = config.errorHandler;

  /**
   * 检查蓝牙权限
   * @returns {Promise} - 权限检查结果的 Promise
   */
  var checkPermissions = function checkPermissions() {
    return new Promise(function (resolve, reject) {
      platformApi.getSetting({
        success: function success(_ref) {
          var authSetting = _ref.authSetting;
          if (authSetting["scope.bluetooth"] === true) return resolve();
          platformApi.authorize({
            scope: "scope.bluetooth",
            success: resolve,
            fail: function fail() {
              platformApi.showModal({
                title: "权限要求",
                content: "需要蓝牙权限以连接设备",
                success: function success(_ref2) {
                  var confirm = _ref2.confirm;
                  return confirm ? platformApi.openSetting() : reject();
                }
              });
            }
          });
        },
        fail: reject
      });
    });
  };

  /**
   * 初始化蓝牙适配器
   * @returns {Promise} - 初始化结果的 Promise
   */
  var initBluetoothAdapter = function initBluetoothAdapter() {
    return new Promise(function (resolve, reject) {
      platformApi.openBluetoothAdapter({
        success: function success() {
          setupBluetoothAdapterListeners();
          resolve();
        },
        fail: function fail(err) {
          if (err.errMsg === "openBluetoothAdapter:fail already opened") {
            setupBluetoothAdapterListeners();
            resolve();
          } else {
            reject(err);
          }
        }
      });
    });
  };

  /**
   * 设置蓝牙适配器监听
   */
  var setupBluetoothAdapterListeners = function setupBluetoothAdapterListeners() {
    // 监听蓝牙适配器状态变化
    platformApi.onBluetoothAdapterStateChange(function (state) {
      console.log("蓝牙适配器状态变化:", state);
      if (!state.available) {
        errorHandler(ErrorTypes$1.BLUETOOTH_CONNECTION_FAILED, "蓝牙已断开", new Error("蓝牙已断开"));
      }
    });
  };

  /**
   * 初始化蓝牙
   * @returns {Promise} - 初始化结果的 Promise
   */
  var initBluetooth = function initBluetooth() {
    return new Promise(/*#__PURE__*/function () {
      var _ref3 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(resolve) {
        var _err, errorMap, message, _t;
        return _regenerator().w(function (_context) {
          while (1) switch (_context.n) {
            case 0:
              _context.p = 0;
              _context.n = 1;
              return checkPermissions();
            case 1:
              console.log("蓝牙已授权");
              _context.n = 2;
              return initBluetoothAdapter();
            case 2:
              console.log("蓝牙已初始化完成");
              resolve(true);
              _context.n = 4;
              break;
            case 3:
              _context.p = 3;
              _t = _context.v;
              resolve(false);
              errorMap = {
                10000: "蓝牙未初始化",
                10001: "蓝牙不可用，请检查手机蓝牙设置",
                10002: "未找到指定设备",
                10003: "连接失败，请重试",
                10004: "未找到指定服务",
                10005: "未找到指定特征值",
                10006: "连接已断开",
                10007: "当前操作不支持",
                10008: "系统蓝牙异常",
                10009: "您的手机系统版本过低（需Android 4.3+）",
                10012: "连接超时",
                10013: "设备ID无效"
              };
              message = errorMap[((_err = err) === null || _err === void 0 ? void 0 : _err.errCode) || ""] || err.message || "蓝牙连接失败";
              errorHandler(ErrorTypes$1.BLUETOOTH_CONNECTION_FAILED, message, _t);
            case 4:
              return _context.a(2);
          }
        }, _callee, null, [[0, 3]]);
      }));
      return function (_x) {
        return _ref3.apply(this, arguments);
      };
    }());
  };

  /**
   * 断开蓝牙适配器
   * @returns {Promise} - 断开结果的 Promise
   */
  var disconnectBluetoothAdapter = function disconnectBluetoothAdapter() {
    return new Promise(function (resolve, reject) {
      platformApi.closeBluetoothAdapter({
        success: function success() {
          console.log("蓝牙适配器已断开");
          resolve();
        },
        fail: function fail(err) {
          reject(new Error("\u65AD\u5F00\u84DD\u7259\u9002\u914D\u5668\u5931\u8D25: ".concat(err.errMsg)));
        }
      });
    });
  };
  return {
    initBluetooth: initBluetooth,
    disconnectBluetoothAdapter: disconnectBluetoothAdapter
  };
}

/**
 * 设备连接功能模块
 * @param {Object} config - 配置项对象
 * @param {string} config.connectionMode - 设备连接方式，'auto' 或 'manual'
 * @param {string} config.serviceId - 设备服务 ID
 * @param {function} config.characteristicMatch - 特征值匹配函数
 * @param {function} config.errorHandler - 异常处理函数
 * @returns {Object} - 包含手动连接和自动连接设备方法的对象
 */
function deviceConnection (config) {
  var serviceId = config.serviceId,
    characteristicMatch = config.characteristicMatch,
    errorHandler = config.errorHandler;
  var deviceList = [];
  var selectedDevice = null;
  var writeChar = null;
  var notifyChar = null;
  var scanTimer = null;
  var scanTime = 10;

  /**
   * 启动设备发现
   * @returns {Promise} - 设备发现结果的 Promise
   */
  var startBluetoothDiscovery = function startBluetoothDiscovery() {
    return new Promise(/*#__PURE__*/function () {
      var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(resolve, reject) {
        var _yield$getBluetoothAd, available;
        return _regenerator().w(function (_context2) {
          while (1) switch (_context2.n) {
            case 0:
              _context2.n = 1;
              return getBluetoothAdapterState();
            case 1:
              _yield$getBluetoothAd = _context2.v;
              available = _yield$getBluetoothAd.available;
              if (available) {
                _context2.n = 2;
                break;
              }
              errorHandler(ErrorTypes$1.BLUETOOTH_CONNECTION_FAILED, "蓝牙适配器不可用", new Error("蓝牙适配器不可用"));
              reject(new Error("蓝牙适配器不可用"));
              return _context2.a(2);
            case 2:
              if (scanTimer) {
                clearTimeout(scanTimer);
              }
              // 等待10s后自动结束
              scanTimer = setTimeout(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
                return _regenerator().w(function (_context) {
                  while (1) switch (_context.n) {
                    case 0:
                      _context.n = 1;
                      return stopBluetoothDiscovery();
                    case 1:
                      if (config.connectionMode === "auto") {
                        autoConnectDevice(false);
                      }
                      resolve();
                    case 2:
                      return _context.a(2);
                  }
                }, _callee);
              })), scanTime * 1000);

              // 开始扫描
              _context2.n = 3;
              return new Promise(function (resolve, reject) {
                platformApi.startBluetoothDevicesDiscovery({
                  services: serviceId ? [serviceId] : void 0,
                  allowDuplicatesKey: false,
                  success: function success() {
                    // 注册发现监听
                    platformApi.onBluetoothDeviceFound(handleDeviceFound);
                    resolve();
                  },
                  fail: function fail(err) {
                    console.log("扫描错误", err);
                    if (err.errMsg.includes("already started")) {
                      resolve();
                    } else {
                      errorHandler(ErrorTypes$1.DEVICE_CONNECTION_FAILED, "\u626B\u63CF\u8BBE\u5907\u5931\u8D25: ".concat(err.errMsg), err);
                      reject(err);
                    }
                  }
                });
              });
            case 3:
              return _context2.a(2);
          }
        }, _callee2);
      }));
      return function (_x, _x2) {
        return _ref.apply(this, arguments);
      };
    }());
  };

  /**
   * 设备发现处理
   * @param {Object} param - 包含设备列表的对象
   * @param {Array} param.devices - 发现的设备列表
   */
  var handleDeviceFound = function handleDeviceFound(_ref3) {
    var devices = _ref3.devices;
    var _devices = devices.filter(function (d) {
      return checkDevice(d);
    });
    function checkDevice(device) {
      var hasUUID = serviceId && device.advertisServiceUUIDs ? device.advertisServiceUUIDs.includes(serviceId) : true;
      return device.connectable !== false && hasUUID && !deviceList.some(function (exist) {
        return exist.deviceId === device.deviceId;
      });
    }
    deviceList = [].concat(_toConsumableArray(deviceList), _toConsumableArray(_devices));

    // 用于暴露发现设备列表
    config.onDeviceFound && config.onDeviceFound(_devices, deviceList);
    if (config.connectionMode === "auto") {
      autoConnectDevice(true);
    }
  };

  /**
   * 停止设备发现
   * @returns {Promise} - 停止结果的 Promise
   */
  var stopBluetoothDiscovery = function stopBluetoothDiscovery() {
    return new Promise(/*#__PURE__*/function () {
      var _ref4 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(resolve, reject) {
        var _yield$getBluetoothAd2, discovering;
        return _regenerator().w(function (_context3) {
          while (1) switch (_context3.n) {
            case 0:
              _context3.n = 1;
              return getBluetoothAdapterState();
            case 1:
              _yield$getBluetoothAd2 = _context3.v;
              discovering = _yield$getBluetoothAd2.discovering;
              if (discovering) {
                platformApi.stopBluetoothDevicesDiscovery({
                  success: function success() {
                    resolve();
                  },
                  fail: function fail(err) {
                    errorHandler(ErrorTypes$1.DEVICE_CONNECTION_FAILED, "\u505C\u6B62\u626B\u63CF\u8BBE\u5907\u5931\u8D25: ".concat(err.errMsg), err);
                    reject(err);
                  }
                });
              } else {
                resolve();
              }
            case 2:
              return _context3.a(2);
          }
        }, _callee3);
      }));
      return function (_x3, _x4) {
        return _ref4.apply(this, arguments);
      };
    }());
  };

  /**
   * 获取蓝牙适配器状态
   * @returns {Promise} - 蓝牙适配器状态的 Promise
   */
  var getBluetoothAdapterState = function getBluetoothAdapterState() {
    return new Promise(function (resolve) {
      platformApi.getBluetoothAdapterState({
        success: resolve,
        fail: function fail() {
          return resolve({
            available: false,
            discovering: false
          });
        }
      });
    });
  };

  /**
   * 设备连接核心逻辑
   * @param {Object} device - 要连接的设备对象
   * @returns {Promise} - 设备连接结果的 Promise
   */
  var connectDevice = function connectDevice(device) {
    return new Promise(/*#__PURE__*/function () {
      var _ref5 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(resolve, reject) {
        var services, primaryService, characteristics, _characteristicMatch, _writeChar, _notifyChar, _t;
        return _regenerator().w(function (_context4) {
          while (1) switch (_context4.n) {
            case 0:
              _context4.p = 0;
              console.log("开始连接设备", device);
              // 1. 创建BLE连接
              _context4.n = 1;
              return createBLEConnection(device.deviceId);
            case 1:
              _context4.n = 2;
              return getBLEDeviceServices(device.deviceId);
            case 2:
              services = _context4.v;
              primaryService = services.find(function (s) {
                return s.uuid === serviceId;
              });
              if (primaryService) {
                _context4.n = 3;
                break;
              }
              throw new Error("未找到指定服务");
            case 3:
              _context4.n = 4;
              return getBLEDeviceCharacteristics(device.deviceId, primaryService.uuid);
            case 4:
              characteristics = _context4.v;
              _characteristicMatch = characteristicMatch(characteristics), _writeChar = _characteristicMatch.writeChar, _notifyChar = _characteristicMatch.notifyChar;
              if (!(!_writeChar || !_notifyChar)) {
                _context4.n = 5;
                break;
              }
              throw new Error("缺少必要特征值");
            case 5:
              selectedDevice = device;
              _readOnlyError("writeChar");
              _readOnlyError("notifyChar");

              // 4. 启用通知
              _context4.n = 6;
              return enableNotifications(device.deviceId, primaryService.uuid, _notifyChar.uuid);
            case 6:
              setupDeviceListeners(device.deviceId);
              resolve();
              _context4.n = 8;
              break;
            case 7:
              _context4.p = 7;
              _t = _context4.v;
              if (_t.message === "未找到指定服务") {
                errorHandler(ErrorTypes$1.SERVICE_NOT_FOUND, _t.message, _t);
              } else if (_t.message === "缺少必要特征值") {
                errorHandler(ErrorTypes$1.CHARACTERISTIC_NOT_FOUND, _t.message, _t);
              } else {
                errorHandler(ErrorTypes$1.DEVICE_CONNECTION_FAILED, _t.message, _t);
              }
              reject(_t);
            case 8:
              return _context4.a(2);
          }
        }, _callee4, null, [[0, 7]]);
      }));
      return function (_x5, _x6) {
        return _ref5.apply(this, arguments);
      };
    }());
  };

  /**
   * 创建BLE连接
   * @param {string} deviceId - 设备 ID
   * @returns {Promise} - 连接结果的 Promise
   */
  var createBLEConnection = function createBLEConnection(deviceId) {
    return new Promise(function (resolve, reject) {
      platformApi.createBLEConnection({
        deviceId: deviceId,
        success: function success() {
          resolve();
        },
        fail: function fail(err) {
          errorHandler(ErrorTypes$1.DEVICE_CONNECTION_FAILED, "\u8FDE\u63A5\u5931\u8D25: ".concat(err.errMsg), err);
          reject(new Error("\u8FDE\u63A5\u5931\u8D25: ".concat(err.errMsg)));
        }
      });
    });
  };

  /**
   * 获取BLE设备服务
   * @param {string} deviceId - 设备 ID
   * @returns {Promise} - 服务列表的 Promise
   */
  var getBLEDeviceServices = function getBLEDeviceServices(deviceId) {
    return new Promise(function (resolve, reject) {
      platformApi.getBLEDeviceServices({
        deviceId: deviceId,
        success: function success(res) {
          return resolve(res.services);
        },
        fail: function fail(err) {
          errorHandler(ErrorTypes$1.SERVICE_NOT_FOUND, "\u83B7\u53D6\u670D\u52A1\u5931\u8D25: ".concat(err.errMsg), err);
          reject(new Error("\u83B7\u53D6\u670D\u52A1\u5931\u8D25: ".concat(err.errMsg)));
        }
      });
    });
  };

  /**
   * 获取BLE设备特征值
   * @param {string} deviceId - 设备 ID
   * @param {string} serviceId - 服务 ID
   * @returns {Promise} - 特征值列表的 Promise
   */
  var getBLEDeviceCharacteristics = function getBLEDeviceCharacteristics(deviceId, serviceId) {
    return new Promise(function (resolve, reject) {
      platformApi.getBLEDeviceCharacteristics({
        deviceId: deviceId,
        serviceId: serviceId,
        success: function success(res) {
          return resolve(res.characteristics);
        },
        fail: function fail(err) {
          errorHandler(ErrorTypes$1.CHARACTERISTIC_NOT_FOUND, "\u83B7\u53D6\u7279\u5F81\u503C\u5931\u8D25: ".concat(err.errMsg), err);
          reject(new Error("\u83B7\u53D6\u7279\u5F81\u503C\u5931\u8D25: ".concat(err.errMsg)));
        }
      });
    });
  };

  /**
   * 启用通知
   * @param {string} deviceId - 设备 ID
   * @param {string} serviceId - 服务 ID
   * @param {string} characteristicId - 特征值 ID
   * @returns {Promise} - 启用结果的 Promise
   */
  var enableNotifications = function enableNotifications(deviceId, serviceId, characteristicId) {
    return new Promise(function (resolve, reject) {
      platformApi.notifyBLECharacteristicValueChange({
        deviceId: deviceId,
        serviceId: serviceId,
        characteristicId: characteristicId,
        state: true,
        success: function success() {
          platformApi.onBLECharacteristicValueChange(handleDataReceived);
          resolve();
        },
        fail: function fail(err) {
          errorHandler(ErrorTypes$1.NOTIFICATION_ENABLE_FAILED, "\u542F\u7528\u901A\u77E5\u5931\u8D25: ".concat(err.errMsg), err);
          reject(new Error("\u542F\u7528\u901A\u77E5\u5931\u8D25: ".concat(err.errMsg)));
        }
      });
    });
  };

  /**
   * 设备事件监听设置
   * @param {string} deviceId - 设备 ID
   */
  var setupDeviceListeners = function setupDeviceListeners(deviceId) {
    // 连接状态监听
    platformApi.onBLEConnectionStateChange(function (res) {
      console.log("连接状态", res);
      if (!res.connected) {
        errorHandler(ErrorTypes$1.DEVICE_CONNECTION_FAILED, "设备已断开", new Error("设备已断开"));
      }
    });
  };

  /**
   * 手动连接设备
   */
  var connectDeviceManually = /*#__PURE__*/function () {
    var _ref6 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(device) {
      var _t2;
      return _regenerator().w(function (_context5) {
        while (1) switch (_context5.n) {
          case 0:
            _context5.p = 0;
            _context5.n = 1;
            return stopBluetoothDiscovery();
          case 1:
            _context5.n = 2;
            return connectDevice(device);
          case 2:
            console.log("设备连接成功", device);
            _context5.n = 4;
            break;
          case 3:
            _context5.p = 3;
            _t2 = _context5.v;
            console.error(_t2);
          case 4:
            return _context5.a(2);
        }
      }, _callee5, null, [[0, 3]]);
    }));
    return function connectDeviceManually(_x7) {
      return _ref6.apply(this, arguments);
    };
  }();

  /**
   * 自动连接设备
   * @param {boolean} isDiscovery - 是否设备发现中
   */
  var autoConnectDevice = /*#__PURE__*/function () {
    var _ref7 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6(isDiscovery) {
      var device, _t3;
      return _regenerator().w(function (_context6) {
        while (1) switch (_context6.n) {
          case 0:
            _context6.p = 0;
            if (!(deviceList.length > 0)) {
              _context6.n = 3;
              break;
            }
            device = deviceList[0];
            _context6.n = 1;
            return stopBluetoothDiscovery();
          case 1:
            _context6.n = 2;
            return connectDevice(device);
          case 2:
            console.log("设备连接成功", device);
            _context6.n = 4;
            break;
          case 3:
            !isDiscovery && errorHandler(ErrorTypes$1.DEVICE_NOT_FOUND, "未找到可用设备", new Error("未找到可用设备"));
          case 4:
            _context6.n = 6;
            break;
          case 5:
            _context6.p = 5;
            _t3 = _context6.v;
            console.error(_t3);
          case 6:
            return _context6.a(2);
        }
      }, _callee6, null, [[0, 5]]);
    }));
    return function autoConnectDevice(_x8) {
      return _ref7.apply(this, arguments);
    };
  }();

  /**
   * 获取设备信息
   * @returns {Object} - 设备信息对象
   */
  var getDeviceInfo = function getDeviceInfo() {
    return {
      selectedDevice: selectedDevice,
      writeChar: writeChar,
      notifyChar: notifyChar
    };
  };

  /**
   * 断开蓝牙设备连接
   * @returns {Promise} - 断开连接结果的 Promise
   */
  var disconnectDevice = function disconnectDevice() {
    return new Promise(function (resolve, reject) {
      if (!selectedDevice) {
        errorHandler(ErrorTypes$1.DEVICE_CONNECTION_FAILED, "没有已连接的设备", new Error("没有已连接的设备"));
        reject(new Error("没有已连接的设备"));
        return;
      }
      platformApi.closeBLEConnection({
        deviceId: selectedDevice.deviceId,
        success: function success() {
          selectedDevice = null;
          writeChar = null;
          notifyChar = null;
          resolve();
        },
        fail: function fail(err) {
          errorHandler(ErrorTypes$1.DEVICE_CONNECTION_FAILED, "\u65AD\u5F00\u8FDE\u63A5\u5931\u8D25: ".concat(err.errMsg), err);
          reject(new Error("\u65AD\u5F00\u8FDE\u63A5\u5931\u8D25: ".concat(err.errMsg)));
        }
      });
    });
  };
  return {
    connectDevice: connectDeviceManually,
    startBluetoothDiscovery: startBluetoothDiscovery,
    stopBluetoothDiscovery: stopBluetoothDiscovery,
    getDeviceInfo: getDeviceInfo,
    disconnectDevice: disconnectDevice
  };
}

/**
 * 设备测量功能模块
 * @param {Object} config - 配置项对象
 * @param {function} config.communicationData - 设备发送通信数据的生成函数
 * @param {function} config.errorHandler - 异常处理函数
 * @returns {Object} - 包含开始测量方法的对象
 */
function deviceMeasurement (config) {
  var communicationData = config.communicationData,
    errorHandler = config.errorHandler,
    serviceId = config.serviceId;
  var selectedDevice = null;
  var writeChar = null;
  var notifyChar = null;
  var measureData = null;

  /**
   * 设置设备信息
   * @param {Object} device - 设备对象
   * @param {Object} char - 特征值对象
   * @param {string} sId - 服务 ID
   */
  var setDeviceInfo = function setDeviceInfo(_device, _writeChar, _notifyChar) {
    selectedDevice = _device;
    writeChar = _writeChar;
    notifyChar = _notifyChar;
  };

  /**
   * 开始测量
   */
  var startMeasurement = function startMeasurement() {
    if (!selectedDevice || !writeChar || !notifyChar) {
      errorHandler(ErrorTypes.DEVICE_CONNECTION_FAILED, '设备未连接或特征值未获取', new Error('设备未连接或特征值未获取'));
      return;
    }
    var buffer = communicationData();
    platformApi.writeBLECharacteristicValue({
      deviceId: selectedDevice.deviceId,
      serviceId: serviceId,
      characteristicId: writeChar.uuid,
      value: buffer,
      success: function success(res) {
        console.log('发送指令成功', res);
        // 处理测量结果
        platformApi.onBLECharacteristicValueChange(handleDataReceived);
      },
      fail: function fail(res) {
        errorHandler(res);
      }
    });
  };

  /**
   * 处理测量结果
   * @param {Object} res - 测量结果对象
   */
  var handleDataReceived = function handleDataReceived(res) {
    console.log('测量结果', res);
    // 处理测量结果的逻辑
    measureData = res;
  };

  /**
   * 获取测量数据
   * @returns {Object} - 测量数据对象
   */
  var getMeasureData = function getMeasureData() {
    return measureData;
  };
  return {
    startMeasurement: startMeasurement,
    setDeviceInfo: setDeviceInfo,
    getMeasureData: getMeasureData
  };
}

/**
 * 设备上报功能模块
 * @param {Object} config - 配置项对象
 * @param {function} config.reportMethod - 设备上报方式的处理函数
 * @param {function} config.reportDataHandler - 上报数据处理函数
 * @param {function} config.errorHandler - 异常处理函数
 * @returns {Object} - 包含上报数据方法的对象
 */
function deviceReport (config) {
  var reportMethod = config.reportMethod,
    reportDataHandler = config.reportDataHandler,
    errorHandler = config.errorHandler;
  var measureData = null;

  /**
   * 设置测量数据
   * @param {Object} data - 测量数据对象
   */
  var setMeasureData = function setMeasureData(data) {
    measureData = data;
  };

  /**
   * 上报数据
   */
  var reportData = function reportData() {
    if (!measureData) {
      errorHandler(ErrorTypes.NO_MEASUREMENT_DATA, '没有测量数据可供上报', new Error('没有测量数据可供上报'));
      return;
    }
    var processedData = reportDataHandler(measureData);
    try {
      reportMethod(processedData);
    } catch (error) {
      errorHandler(ErrorTypes.NO_MEASUREMENT_DATA, error.message, error);
    }
  };
  return {
    reportData: reportData,
    setMeasureData: setMeasureData
  };
}

// 引入各个功能模块

/**
 * 初始化函数，用于合并所有功能并返回可调用的方法
 * @param {Object} config - 配置项对象
 * @param {string} config.connectionMode - 设备连接方式，'auto' 或 'manual'
 * @param {string} config.serviceId - 设备服务 ID
 * @param {function} config.onDeviceFound - 设备发现处理函数
 * @param {function} config.characteristicMatch - 特征值匹配函数
 * @param {function} config.communicationData - 设备发送通信数据的生成函数
 * @param {function} config.reportMethod - 设备上报方式的处理函数
 * @param {function} config.errorHandler - 异常处理函数
 * @param {function} config.reportDataHandler - 上报数据处理函数
 * @returns {Object} - 包含四个功能方法的对象
 */
function BluetoothPlugin(config) {
  // 默认配置项
  var defaultConfig = {
    connectionMode: 'auto',
    // 'auto' or 'manual'
    serviceId: '',
    onDeviceFound: function onDeviceFound(devices, deviceList) {
      console.log('设备发现:', devices);
      console.log('设备列表:', deviceList);
    },
    characteristicMatch: function characteristicMatch(characteristics) {
      var writeChar = characteristics.find(function (c) {
        return c.properties.write;
      });
      var notifyChar = characteristics.find(function (c) {
        return c.properties.notify;
      });
      return {
        writeChar: writeChar,
        notifyChar: notifyChar
      };
    },
    communicationData: function communicationData() {
      var buffer = new ArrayBuffer(6);
      var dataView = new DataView(buffer);
      dataView.setUint8(0, 0x02);
      dataView.setUint8(1, 0x40);
      dataView.setUint8(2, 0xdc);
      dataView.setUint8(3, 0x01);
      dataView.setUint8(4, 0xa1);
      dataView.setUint8(5, 0x3c);
      return buffer;
    },
    reportDataHandler: function reportDataHandler(data) {
      return data;
    },
    reportMethod: function reportMethod(data) {
      console.log('Reporting data:', data);
    },
    errorHandler: function errorHandler(err) {
      console.log('Error:', err);
    }
  };
  // 合并用户配置和默认配置
  config = Object.assign({}, defaultConfig, config);

  // 初始化蓝牙连接功能
  var _bluetoothConnection = bluetoothConnection(config),
    initBluetooth = _bluetoothConnection.initBluetooth,
    disconnectBluetoothAdapter = _bluetoothConnection.disconnectBluetoothAdapter;
  // 初始化设备连接功能
  var _deviceConnection = deviceConnection(config),
    connectDevice = _deviceConnection.connectDevice,
    startBluetoothDiscovery = _deviceConnection.startBluetoothDiscovery,
    stopBluetoothDiscovery = _deviceConnection.stopBluetoothDiscovery,
    getDeviceInfo = _deviceConnection.getDeviceInfo,
    disconnectDevice = _deviceConnection.disconnectDevice;
  // 初始化设备测量功能
  var _deviceMeasurement = deviceMeasurement(config),
    _startMeasurement = _deviceMeasurement.startMeasurement,
    setDeviceInfo = _deviceMeasurement.setDeviceInfo,
    getMeasureData = _deviceMeasurement.getMeasureData;
  // 初始化设备上报功能
  var _deviceReport = deviceReport(config),
    _reportData = _deviceReport.reportData,
    setMeasureData = _deviceReport.setMeasureData;

  // 返回可调用的方法
  return {
    connectBluetooth: initBluetooth,
    disconnectBluetoothAdapter: disconnectBluetoothAdapter,
    startBluetoothDiscovery: startBluetoothDiscovery,
    stopBluetoothDiscovery: stopBluetoothDiscovery,
    connectDevice: connectDevice,
    disconnectDevice: disconnectDevice,
    startMeasurement: function startMeasurement() {
      setDeviceInfo(getDeviceInfo());
      _startMeasurement();
    },
    reportData: function reportData() {
      setMeasureData(getMeasureData());
      _reportData();
    }
  };
}

export { BluetoothPlugin, ErrorTypes$1 as ErrorTypes };
